var map;
var geocoder;
var directionsDisplay;
var directionsService;
var map_info = {id: '#map-canvas2',jsid: 'map-canvas2',modal: '#modal-map'};
var aPoint = {position: null,marker: null,info_ball: null,input_name: 'start',input_box: $('#start'),image: $(map_info.id).attr('data-mk-a')};
var bPoint = {shop_name: null, position: null,marker: null,info_ball: null,input_name: 'end',input_box: $('#end'),image: $(map_info.id).attr('data-mk-b')};

$(document).ready(function(){
    if(typeof google !== typeof undefined){
        map               = new google.maps.Map(document.getElementById(map_info.jsid), {});
        geocoder          = new google.maps.Geocoder();
        directionsService = new google.maps.DirectionsService();
        directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
        aPoint.info_ball  = new google.maps.InfoWindow();
        bPoint.info_ball  = new google.maps.InfoWindow();
        $(map_info.modal).on('shown.bs.modal', function () {
            google.maps.event.trigger(map, "resize");
            directionsDisplay.setMap(map);
            autocompleteAddress(document.getElementById(aPoint.input_name), aPoint);
            autocompleteAddress(document.getElementById(bPoint.input_name), bPoint);
            detectLocation();
            if(bPoint.input_box.val()!=''){
                getShopMarker(bPoint.input_box.val());
            }
        });
        $(document.body).on('click', '#btn-show-direction', function(){
            calcRoute(aPoint.input_box.val(), bPoint.input_box.val());
        });
        $(document.body).on('click', '#btn-detect-location', detectLocation);    
    }    
});

function autocompleteAddress(input, objPoint){
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place = autocomplete.getPlace();
        if(typeof place.location!== typeof undefined){
            objPoint.position = new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng());
            dropMaker(objPoint);
            reserveGeoCode(objPoint);
            calcRoute(aPoint.input_box.val(), bPoint.input_box.val());
        }
    });
}

function calcRoute(start, end) {
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

function getShopMarker(address){
    var shopName = $(map_info.id).attr('data-shop-name');
    if(shopName!=''){
        shopName = '<h4><strong>' + shopName + '</strong></h4>';
    }
    geocoder.geocode({'address': address}, function(results, status) {
        if(status == google.maps.GeocoderStatus.ZERO_RESULTS){

        } else if (status == google.maps.GeocoderStatus.OK) {
            bPoint.shop_name = shopName;
            bPoint.position = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
            dropMaker(bPoint);
            reserveGeoCode(bPoint);
            calcRoute(aPoint.input_box.val(), bPoint.input_box.val());
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

function detectLocation(){
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            aPoint.position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            aPoint.cur_name = '<h4><strong>Vị trí hiện tại</strong></h4>';
            aPoint.waitCalRoute = 1;
            dropMaker(aPoint);
            reserveGeoCode(aPoint);
        }, function() {
            handleNoGeolocation(true);
        });
    } else {
        handleNoGeolocation(false);
    }
}

function dropMaker(objPoint){
    if(objPoint.marker!=null){
        objPoint.marker.setMap(null);
    }
    objPoint.marker = new google.maps.Marker({
        map: map,
        position: objPoint.position,
        icon: objPoint.image,
        draggable:true,
        animation: google.maps.Animation.DROP
    });
    google.maps.event.addListener(objPoint.marker,'dragend',function(event){
        objPoint.position = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
        reserveGeoCode(objPoint);
    });
    map.setCenter(objPoint.position);
    map.setZoom(12);
}

function reserveGeoCode(objPoint){
    var latlng = new google.maps.LatLng(objPoint.position.lat(), objPoint.position.lng());
    geocoder.geocode({'latLng': objPoint.position}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                objPoint.input_box.val(results[0].formatted_address);
                if(objPoint.shop_name!=undefined){
                    objPoint.info_ball.setContent(objPoint.shop_name + results[0].formatted_address);    
                } else if(objPoint.cur_name!=undefined) {
                    objPoint.info_ball.setContent(objPoint.cur_name + results[0].formatted_address);
                }
                if(objPoint.waitCalRoute!=undefined){
                    calcRoute(aPoint.input_box.val(), bPoint.input_box.val());
                }
                objPoint.info_ball.open(map, objPoint.marker);
            }
        }
    });
}

function handleNoGeolocation(errorFlag) {
    if (errorFlag) {
        var content = 'Error: The Geolocation service failed.';
    } else {
        var content = 'Error: Your browser doesn\'t support geolocation.';
    }
    var options = {
        map: map,
        position: new google.maps.LatLng(60, 105),
        content: content
    };
    var aInfo = new google.maps.InfoWindow(options);
    map.setCenter(options.position);
}